package com.five.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.five.entity.*;
import com.five.service.*;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家活动
 * Created by Administrator on 2018/2/25.
 */
@RestController
@RequestMapping("/youxue")
public class BusinessActivityController {

    private static final Logger looger = Logger.getLogger(BusinessActivityController.class);

    @Autowired
    private BusinessActivityService businessActivityService;
    @Autowired
    private FileGroupService fileGroupService;
    @Autowired
    private FileService fileService;
    @Autowired
    private UserBusinessActivitiesService userBusinessActivitiesService;
    @Autowired
    private UserService userService;
    @Autowired
    HttpServletRequest request;

    /**
     * 商家发布活动->待测试
     *
     * @param data
     * @param file
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/publishBusinessActivity", method = RequestMethod.GET)
    public String publishBusinessActivity(@RequestParam("data") String data,
                                         @RequestParam("file") MultipartFile file[]) throws ParseException {

        User currentUser =
                (User) request.getSession().getAttribute("userLogin");
        looger.info(data);
        if (currentUser.getType().equals("商家")) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String activityTitle = jsonObject.getString("activityTitle");
            String activityDescription = jsonObject.getString("activityDescription");
            Integer activityNumber = jsonObject.getInteger("activityNumber");
            Integer activityLowerNumber = jsonObject.getInteger("activityLowerNumber");
            Integer activityPrice = jsonObject.getInteger("activityPrice");
            String activityType = jsonObject.getString("activityType");
            String activityName = jsonObject.getString("activityName");
            String activityStartTime = jsonObject.getString("activityStartTime");
            String activityEndTime = jsonObject.getString("activityEndTime");
            String activityArea = jsonObject.getString("activityArea");
            String activityLine = jsonObject.getString("activityLine");

            FileGroup fileGroup = new FileGroup();
            fileGroup.setGroupName(activityType);
            fileGroupService.addFileGroup(fileGroup);

            BusinessActivities businessActivities = new BusinessActivities();
            businessActivities.setActivityTitle(activityTitle);
            businessActivities.setActivityDescription(activityDescription);
            businessActivities.setActivityNumber(activityNumber);
            businessActivities.setActivityLowerNumber(activityLowerNumber);
            businessActivities.setActivityPrice(activityPrice);
            businessActivities.setActivityType(activityType);
            businessActivities.setAvtivityName(activityName);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            businessActivities.setActivityStartTime(sdf.parse(activityStartTime));
            businessActivities.setActivityEndTime(sdf.parse(activityEndTime));
            businessActivities.setActivityArea(activityArea);
            businessActivities.setActivityLine(activityLine);
            businessActivities.setUserId(currentUser.getUserId());
            businessActivities.setActivityFileGroupId(fileGroup.getId());
            businessActivityService.addBusinessActivity(businessActivities);

            String savePath = "F:\\AllJavaWeb\\YouXue\\src\\main\\webapp\\upload";

            String newFileName = null;
            String filePath = null;
            long size = 0;
            String suffixName = null;
            if (file != null) {
                for (MultipartFile file1 : file) {

                    //获取文件名称
                    String fileName = file1.getOriginalFilename();
                    //获取后缀名
                    suffixName = fileName.substring(fileName.indexOf(".") + 1);
                    //图片大小
                    size = file1.getSize();
                    //新文件名称
                    newFileName = System.currentTimeMillis() + "." + suffixName;
                    //新文件路劲
                    filePath = savePath + "\\" + newFileName;
                    //获取存储文件路径
                    java.io.File fileDir = new java.io.File(savePath);
                    if (!fileDir.exists()) {
                        //如果文件夹没有：新建
                        fileDir.mkdirs();
                    }
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(filePath);
                        fos.write(file1.getBytes());
                        fos.flush();
                    } catch (Exception e) {
                        e.printStackTrace();

                    } finally {
                        try {
                            if (fos != null) {
                                fos.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();

                        }
                    }

                    File file2 = new File();
                    file2.setFileGroupId(fileGroup.getId());
                    file2.setFileRealName("upload" + "/" + newFileName);
                    file2.setFileSize(size);
                    fileService.addFile(file2);
                }
                return "{\"result\":\"true\",\"msg\":\"success\"}";
            }else {
                return "{\"result\":\"true\",\"msg\":\"file is null\"}";
            }
        } else {
            return "you are not business";
        }
    }


    /**
     * 商家的活动
     * @return
     */
    @RequestMapping(value = "/myActivity",method = RequestMethod.GET,produces ="text/plain;charset=UTF-8")
    public String myActivity(){
        User currentUser =
                (User) request.getSession().getAttribute("userLogin");
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        Map<String,Object> map;
        if (currentUser.getType().equals("商家")){
            List<BusinessActivities> businessActivities = null;
            try {
                businessActivities = businessActivityService.selectActivitiesByUserId(currentUser.getUserId());
            }catch (Exception e){
                looger.info("第一异常");
                return "";
            }
            for (BusinessActivities businessActivities1:businessActivities) {
                map = new HashMap<String,Object>();
                map.put("businessActivities",businessActivities1);
                looger.info(businessActivities1.getActivityFileGroupId());

                List<File> files = null;
                try {
                    files = fileService.selectFiles(businessActivities1.getActivityFileGroupId());
                    map.put("file",files);
                }catch (Exception e){
                    map.put("file","");
                    looger.info("1:"+e.getMessage());
                }

                List<UserBusinessActivities> userBusinessActivities = null;
                try {
                    userBusinessActivities = userBusinessActivitiesService.selectUserBusinessActivities(businessActivities1.getId());
                    looger.info(userBusinessActivities.size());
                    List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
                    Map<String,Object> map1 ;
                    for (UserBusinessActivities userBusinessActivities1:userBusinessActivities) {
                        map1 = new HashMap<String, Object>();
                        map1.put("users",userService.getUserById(userBusinessActivities1.getUserId()));
                        map1.put("user-status",userBusinessActivities1.getStatus());
                        list.add(map1);
                    }
                    looger.info(list.size());
                    map.put("user",list);
                    looger.info(JSON.toJSONString(map.get("user")));
                }catch (Exception e){
                    map.put("user","");
                    looger.info("2:"+e.getMessage());
                }
                mapList.add(map);
            }
            return JSON.toJSON(mapList).toString();
        }else {
            return "you are not business!!";
        }

    }

    /**
     * 商家确定用户报名->用户报名成功
     * @param businessActivityId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/confirm",method = RequestMethod.GET)
    public String confirm(@RequestParam("businessActivityId") Integer businessActivityId,
                          @RequestParam("userId") Integer userId){
        UserBusinessActivities userBusinessActivities;
        try {
            userBusinessActivities = userBusinessActivitiesService.selectByUserIdAndBusinessActivityId(userId,businessActivityId);
            userBusinessActivities.setStatus(1);
            userBusinessActivities.setId(userBusinessActivities.getId());
            userBusinessActivitiesService.updateStatus(userBusinessActivities);
            return "success";
        }catch (Exception e){
            looger.debug(e);
            return "failure";
        }
    }

    /**
     * 用户报名活动
     * @param businessActivityId
     */
    @RequestMapping(value = "/enroll",method = RequestMethod.GET)
    public void enroll(@RequestParam("businessActivityId") Integer businessActivityId){
        User currentUser =
                (User) request.getSession().getAttribute("userLogin");
        if (currentUser.getType().equals("用户")){
            UserBusinessActivities userBusinessActivities = new UserBusinessActivities();
            userBusinessActivities.setUserId(currentUser.getUserId());
            userBusinessActivities.setBusinessActivitiesId(businessActivityId);
            userBusinessActivities.setStatus(0);
            userBusinessActivitiesService.addUserBusinessActivities(userBusinessActivities);
        }
    }


    /**
     * 用户的活动
     * @return
     */
    @RequestMapping(value = "/userActivities",method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
    public String userActivities(){
        User currentUser =
                (User) request.getSession().getAttribute("userLogin");
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        Map<String,Object> map;
        if (currentUser.getType().equals("用户")){
            List<UserBusinessActivities> userBusinessActivities = null;
            try {
                userBusinessActivities = userBusinessActivitiesService.selectByUserId(currentUser.getUserId());
            }catch (Exception e){
                looger.info("0:"+e.getMessage());
                return "";
            }

            for (UserBusinessActivities userBusinessActivities1:userBusinessActivities) {
                map = new HashMap<String, Object>();
                map.put("userStatus",userBusinessActivities1.getStatus());
                BusinessActivities businessActivities =
                        businessActivityService.selectByPrimaryKey(userBusinessActivities1.getBusinessActivitiesId());
                map.put("businessActivities",businessActivities);

                List<File> files = null;
                try {
                    files = fileService.selectFiles(businessActivities.getActivityFileGroupId());
                    map.put("file",files);
                }catch (Exception e){
                    map.put("file","");
                    looger.info("1:"+e.getMessage());
                }

                mapList.add(map);
            }
            return JSON.toJSON(mapList).toString();
        }else {
            return "you are not user!!";
        }
    }

    /**
     * 用户取消报名
     * @param businessActivityId
     * @return
     */
    @RequestMapping(value = "/cancel",method = RequestMethod.GET)
    public String cancel(@RequestParam("businessActivityId") Integer businessActivityId){
        User currentUser =
                (User) request.getSession().getAttribute("userLogin");
        if (currentUser.getType().equals("用户")){
            UserBusinessActivities userBusinessActivities =
                    userBusinessActivitiesService.selectByUserIdAndBusinessActivityId(currentUser.getUserId(),businessActivityId);
            userBusinessActivities.setStatus(2);
            userBusinessActivities.setId(userBusinessActivities.getId());
            userBusinessActivitiesService.updateStatus(userBusinessActivities);
            return "success";
        }
        return "failure";
    }



}
